package com.jjh.service.impl;

import com.jjh.consts.Key;
import com.jjh.consts.ResEnum;
import com.jjh.consts.Result;
import com.jjh.pojo.User;
import com.jjh.pojo.vo.LoginUser;
import com.jjh.service.LoginAndRegisterService;
import com.jjh.service.UserService;
import com.jjh.utils.JwtUtil;
import com.jjh.utils.MD5Util;
import com.jjh.utils.RedisUtils;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class LoginAndRegisterServiceImpl implements LoginAndRegisterService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Result login(HttpServletRequest request, HttpServletResponse response,LoginUser loginUser) {



        String username = loginUser.getUsername();
        if(ObjectUtils.isEmpty(username) || "".equals(username)){
            return Result.error(ResEnum.NULL_LOGIN_ERROR,"用户名为空");
        }
        String password = loginUser.getPassword();
        if(ObjectUtils.isEmpty(password)||"".equals(password)){
            return Result.error(ResEnum.NULL_LOGIN_ERROR,"密码为空");
        }
        String checkCode = loginUser.getCode();

        //获取context中的验证码
        ServletContext servletContext = request.getServletContext();
        String captcha = (String) servletContext.getAttribute("captcha");

       if(!checkCode.equals(captcha)){
           return Result.error("验证码错误");
       }
       //验证码正确，清除验证码
        servletContext.removeAttribute("captcha");

       //都没错，然后查询数据库
        User user = userService.getByUserName(username);
       if(ObjectUtils.isEmpty(user)){
           return Result.error("该用户不存在");
       }
       //先对传输过来的密码进行md5加密
        String encodePass = MD5Util.encode(password);
       //进行比对
        if(!encodePass.equals(user.getPassword())){
            return Result.error("密码错误!");
        }
        //给响应头设置token
        String token = new JwtUtil().createToken(user.getId(), user.getUsername());
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("token",token);

//        //将当前用户保存到threadLocal中
//        UserThreadLocal.set(user);
         //将用户保存到redis中
         redisUtils.setString(Key.USER +user.getId(),user.toString());
         return Result.ok(map);
    }

    @Override
    public Result register(User user) {
        return null;
    }

    /**
     * 生成验证码
     * @return 验证码
     */
    @Override
    public Result getCheckCode(HttpServletRequest request) {
        Random random = new Random();
        int checkCode = random.nextInt(9000)+1000;
        String captcha = String.valueOf(checkCode);
        //存入threadLocal中,先清除原来的
        request.getServletContext().setAttribute("captcha",captcha);

        System.out.println("生成验证码："+captcha);
        //返回前端验证码
        return Result.ok(checkCode);
    }

    /**
     * 退出登录
     * @param username
     * @return
     */
    @Override
    public Result logout(String username) {
        if(ObjectUtils.isEmpty(username)){
            return Result.error("用户名不能为空!");
        }
        //查询出来用户为了获取id
        User user = userService.getByUserName(username);
        Integer id = user.getId();
        //把redis中的user数据删除
        redisUtils.deleteString(Key.USER+id);

        return Result.ok("退出登录成功!");
    }
}
